package com.atguigu.lease.web.admin.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * ClassName: StringToBaseEnumConverterFactory
 * Package: com.atguigu.lease.web.admin.converter
 * Description:获取所有枚举值遍历获取枚举值的code与目标参数做对比
 *
 * @Author ygf
 * @Create 2024/9/26 17:26
 * @Version 1.0
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                T[] enumConstants = targetType.getEnumConstants();
                //遍历
                for (T enumConstant : enumConstants) {
                    //判断
                    if (enumConstant.getCode().equals(Integer.parseInt(source))) {
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("非法参数");
            }
        };
    }
}

